package org.example.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.pojo.Job;

import java.util.*;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import java.lang.System;

public class JobAnalyzer {
    public List<Map.Entry<String, Integer>> analyzeRequirements(List<Job> jobs,Integer max_size) {
        StringBuilder allRequirements = new StringBuilder();
        for (Job job : jobs) {
            if (allRequirements.length() > 0) {
                allRequirements.append(",");
            }
            allRequirements.append(job.getWorkRequirements());
//            allRequirements.append(job.getWorkField());
        }

        // Split the string into an array of words
        String[] requirementsArray = allRequirements.toString().split(",");

        // Use a HashMap to count the frequency of each word
        Map<String, Integer> wordCount = new HashMap<>();

        for (String requirement : requirementsArray) {
            // Remove leading/trailing spaces, convert to lower case, remove content in parentheses, and '无', then remove all white spaces
            requirement = requirement.trim().toLowerCase().replaceAll("\\(.*?\\)", "").replace("无", "").replaceAll("\\s+", "");
            // Count the frequency
            wordCount.put(requirement, wordCount.getOrDefault(requirement, 0) + 1);
        }

        // Sort the entries using Stream API
        List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(wordCount.entrySet());
        sortedEntries.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
        // Take the top 30 entries
        int size = Math.min(sortedEntries.size(), max_size);

        return sortedEntries.subList(0, size);
    }

    public Map<String, List<Job>> SalaryGroup(List<Job> list){
        list.sort(Comparator.comparingInt(Job::getSalaryYear));
//        计算薪资年份的四分位数点，以便分割数据集
        int size = list.size();
        int q1Index = size / 4; // 第一个四分位数（后25%）
        int q3Index = 3 * size / 4; // 第三个四分位数（前25%）

        // 分别提取三个薪资段的数据
        List<Job> lower25Percent = new ArrayList<>(list.subList(q1Index, size)); // 后25%
        List<Job> middle50Percent = new ArrayList<>(list.subList(q1Index - 1, q3Index)); // 中间50%
        List<Job> upper25Percent = new ArrayList<>(list.subList(0, q3Index - 1)); // 前25%
        // 创建一个 Map 来存储各个薪资段
        Map<String, List<Job>> salarySegments = new HashMap<>();
        salarySegments.put("upper25Percent", lower25Percent);
        salarySegments.put("middle50Percent", middle50Percent);
        salarySegments.put("lower25Percent", upper25Percent);

        return salarySegments;
    }
    public Map<String, String> getWorkYear_low_up(String experience){
        Map<String, String> WorkYear_low_up = new HashMap<>();
        String low_experience="0";
        String up_experience = "0";
        switch (experience) {
            case "0" -> {
                low_experience = "0";
                up_experience = "0";
            }
            case "1" -> {
                low_experience = "1";
                up_experience = "2";
            }
            case "3" -> {
                low_experience = "3";
                up_experience = "4";
            }
            case "5" -> {
                low_experience = "5";
                up_experience = "9";
            }
            case "10" -> {
                low_experience = "10";
                up_experience = "20";
            }
        }
        WorkYear_low_up.put("low_experience",low_experience);
        WorkYear_low_up.put("up_experience",up_experience);
        return WorkYear_low_up;
    }
    public Map<String, String> intGetWorkYear_low_up(Integer experience){
        Map<String, String> WorkYear_low_up = new HashMap<>();
        String low_experience="0";
        String up_experience="0";
        if (experience<=0){
            low_experience="0";
            up_experience="0";
        }
        else if(experience>0 &&experience<3){
            low_experience="1";
            up_experience="2";
        }
        else if(experience>=3 &&experience<5){
            low_experience="3";
            up_experience="4";
        }
        else if(experience>=5 &&experience<10){
            low_experience="5";
            up_experience="10";
        }
        else {
            low_experience="10";
            up_experience="20";
        }
        WorkYear_low_up.put("low_experience",low_experience);
        WorkYear_low_up.put("up_experience",up_experience);
        return WorkYear_low_up;
    }


    public double calculateAverageWorkYear(List<Job> jobList) {
        if (jobList == null || jobList.isEmpty()) {
            return 0; // 防止除以零异常
        }

        int totalYears = 0;
        for (Job job : jobList) {
            totalYears += job.getWorkYear();
        }

        return (double) totalYears / jobList.size();
    }
    public double calculateAverageSalaryYear(List<Job> jobList) {
        if (jobList == null || jobList.isEmpty()) {
            return 0; // 防止除以零异常
        }

        int totalYears = 0;
        for (Job job : jobList) {
            totalYears += job.getSalaryYear();
        }

        return (double) totalYears / jobList.size();
    }
    public Map<String, Integer> countDegreeDistribution(List<Job> jobList) {
        if (jobList == null || jobList.isEmpty()) {
            return new HashMap<>(); // 返回一个空的分布映射
        }

        Map<String, Integer> degreeDistribution = new HashMap<>();

        for (Job job : jobList) {
            String degree = job.getDegree();
            degreeDistribution.put(degree, degreeDistribution.getOrDefault(degree, 0) + 1);
        }

        return degreeDistribution;
    }
    public String callWithMessage(String input_str)
            throws NoApiKeyException, ApiException, InputRequiredException, JsonProcessingException {
        Generation gen = new Generation();
        List<Message> messages = new ArrayList<>();
        Message systemMsg =
                Message.builder().role(Role.SYSTEM.getValue()).content("这个工作的，技术要求，工作领域，角色定位，工作经验是什么 ？技术要求我只需要列出所有可能需要的技术，工作领域简化成一个短语，角色定位简化成一个短语，工作经验为一个短语。结果尽量简洁。").build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(input_str).build();
        messages.add(systemMsg);
        messages.add(userMsg);
        GenerationParam param =
                GenerationParam.builder().model(Generation.Models.QWEN_TURBO).messages(messages)
                        .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                        .apiKey("sk-005abb5377da47c4a3d40bbc68323235")
                        .build();
        GenerationResult result = gen.call(param);
//        System.out.println(JsonUtils.toJson(result));
        String json_result = JsonUtils.toJson(result);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(json_result);
        JsonNode contentNode = rootNode.path("output").path("choices").get(0).path("message").path("content");
        String content = contentNode.asText();
//        System.out.println(content);
        return content;

    }


}
